/*-
 * SelectPhonebookMemoryStorage.java
 *
 * $LastChangedBy:  $
 * $LastChangedRevision:  $
 * $LastChangedDate:  $
 * $HeadURL: $
 *
 * Copyright (c) 2008, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.at;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.googlecode.attention.PhonebookMemoryStorage;


public class SelectPhonebookMemoryStorage
    extends AtCommand<SelectPhonebookMemoryStorage> {

  private ArrayList<PhonebookMemoryStorage> storages;
  private PhonebookMemoryStorage currentStorage;
  private int currentStorageUsed;
  private int currentStorageTotal;
  
  public SelectPhonebookMemoryStorage(
      AtListener<SelectPhonebookMemoryStorage> listener) {
    super(listener);
  }

  @Override
  protected SelectPhonebookMemoryStorage getThis() {
    return this;
  }
  
  /**
   * This will list the supported phonebook memory storages.
   */
  public void prepareTest() {
    setCommand("AT+CPBS=?", Command.TEST);
  }
  
  /**
   * This will list the current phonebook memory storage.
   */
  public void prepareRead() {
    setCommand("AT+CPBS?", Command.READ);
  }
  
  /**
   * This will select the given phonebook memory storage.
   * 
   * @param storage Phonebook memory storage
   */
  public void prepareWrite(final PhonebookMemoryStorage storage) {
    setCommand("AT+CPBS=" + storage.getReference(), Command.WRITE);
  }
  
  /**
   * Parses strings similar to this:<BR>
   * +CPBS: ("SM","ON","ME","DC","MC","RC")
   * <BR><BR>Creates and stores the matched phonebook memory storages for
   * later retrieval.
   * 
   * @see #getPhonebookMemoryStorages()
   */
  @Override
  protected void parseTest(final String response) {
    if (storages == null) {
      storages = new ArrayList<PhonebookMemoryStorage>();
    }
    
    final Pattern pattern = Pattern.compile("\\+CPBS: \\(([^)]+)\\)");
    final Matcher matcher = pattern.matcher(response);
    while (matcher.find()) {
      final Pattern internalPattern = Pattern.compile("\"([^\"]+)\"");
      final Matcher internalMatcher = internalPattern.matcher(matcher.group(1));
      while (internalMatcher.find()) {
        storages.add(PhonebookMemoryStorage.getPhonebookMemoryStorage(
            internalMatcher.group(1)));
      }
    }
  }
  
  /**
   * Parses strings similar to this:<BR>
   * +CPBS: "SM",59,200
   * <BR><BR>Creates and stores the data for later retrieval.
   * 
   * @see #getCurrentStorage()
   * @see #getUsedSpace()
   * @see #getTotalSpace()
   */
  @Override
  protected void parseRead(final String response) {
    final Pattern pattern = Pattern.compile(
        "\\+CPBS: \"([^\"]+)\",([0-9]+),([0-9]+)");
    final Matcher matcher = pattern.matcher(response);
    while (matcher.find()) {
      this.currentStorage = PhonebookMemoryStorage.getPhonebookMemoryStorage(
          matcher.group(1));
      this.currentStorageUsed = Integer.parseInt(matcher.group(2));
      this.currentStorageTotal = Integer.parseInt(matcher.group(3));
    }
  }
  
  @Override
  protected void parseWrite(final String response) {
    // Nothing to do, OK or error returned
  }
  
  public PhonebookMemoryStorage[] getPhonebookMemoryStorages() {
    if (storages == null) {
      storages = new ArrayList<PhonebookMemoryStorage>();
    }
    return storages.toArray(new PhonebookMemoryStorage[storages.size()]);
  }
  
  /**
   * Returns the current storage (if populated with a test command).
   * 
   * @return The current memory storage, or null if not populated
   * @see #prepareTest()
   */
  public PhonebookMemoryStorage getCurrentStorage() {
    return currentStorage;
  }
   
  /**
   * Returns the used space of the current memory storage.
   * 
   * @return The current usage, or 0 if not populated
   * @see #prepareTest()
   */
  public int getUsedSpace() {
    return currentStorageUsed;
  }
  
  
  /**
   * Returns the total space of the current memory storage.
   * 
   * @return The memory storage total space, or 0 if not populated
   * @see #prepareTest()
   */
  public int getTotalSpace() {
    return currentStorageTotal;
  }
}
